package com.lch.webdemo.aop;

import com.lch.webdemo.enums.DataSourceEnum;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * <一句话描述>.
 *
 * @author liuchenhui
 * @date 2018/10/19
 * @since
 */
public class MultipleDataSource extends AbstractRoutingDataSource {

    private static final Logger logger = LoggerFactory.getLogger(MultipleDataSource.class);

    private static final ThreadLocal<DataSourceEnum> DATASOURCE_KEY = new InheritableThreadLocal<>();

    public static void setMaster() {
        logger.debug("MultipleDataSource set to master");
        DATASOURCE_KEY.set(DataSourceEnum.MASTER);
    }

    public static void setSlave() {
        logger.debug("MultipleDataSource set to slave");
        DATASOURCE_KEY.set(DataSourceEnum.SLAVE);
    }

    public static void remove() {
        DATASOURCE_KEY.remove();
    }


    @Override
    protected Object determineCurrentLookupKey() {
        try {
            logger.debug("MultipleDataSource invoke " + DATASOURCE_KEY.get());
            return DATASOURCE_KEY.get();
        } finally {
            setMaster();
        }
    }
}
